﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using AntUnion.FrameWork.Web.Extend;
using AntUnion.FrameWork.Web.Service;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class CRMAccountController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;
        PublicService publicService = new PublicService();
        public CRMAccountController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }

        #region 用户列表
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit, string account = "", int state = -1, string telephone = "", string email = "", string roles = "", int crmUp = 0, string IDNO = "", string registrationTime = "", string IdNo = "")
        {
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.CrmUsers
                           select new
                           {
                               id = y.Id,
                               isdel = y.Isdel,
                               loginName = y.LoginName,
                               fullName = y.Name,
                               state = y.State,
                               telephone = y.Telephone,
                               email = y.Email,
                               roles = _context.TbUserRoles.Any(r => r.UserId == y.Id) ? _context.TbRoles.Where(k => k.Id == _context.TbUserRoles.Where(r => r.UserId == y.Id && r.UserType == 1).Select(k => k.RoleId).FirstOrDefault()).Select(k => k.Remark).FirstOrDefault() : "",
                               level = y.Level,
                               createDate = y.CreateDate,
                               crmUpId = y.CrmUp,
                               //crmUp = y.CrmUp == null ? "" : _context.CrmUsers.Where(up => up.Id == y.CrmUp).Select(k => k.LoginName).FirstOrDefault(),
                               crmUpEmail = (y.CrmUp == null || y.CrmUp == 0) ? "" : _context.CrmUsers.Where(up => up.Id == y.CrmUp).Select(k => k.LoginName).FirstOrDefault(),
                               mt5UpLogin = (y.CrmUp == null || y.CrmUp == 0) ? "" : (_context.Mt5Users.Any(k => k.CrmId == y.CrmUp) ? _context.Mt5Users.Where(k => k.CrmId == y.CrmUp).Select(k => k.Login).FirstOrDefault().ToString() : ""),
                               realAccount = _context.Mt5Users.Where(k => k.CrmId == y.Id && k.Type == 0).Select(k => k.Login).FirstOrDefault(),
                               //simulatedAccount = _context.Mt5Users.Where(k => k.CrmId == y.Id && k.Type == 1).Select(k => k.Login).FirstOrDefault(),
                               IdNo = y.IdNo
                           };
                data = data.Where(k => k.isdel == 0);
                if (!string.IsNullOrEmpty(account))
                {
                    long loginNo = 0;
                    try
                    {
                        loginNo = Convert.ToInt64(account);
                    }
                    catch
                    {
                        loginNo = 0;
                    }
                    if (loginNo == 0)
                    {
                        data = data.Where(k => k.loginName.Contains(account) || k.fullName.Contains(account));
                    }
                    else
                    {
                        data = data.Where(k => k.loginName.Contains(account) || k.fullName.Contains(account) || k.realAccount == loginNo);
                    }
                }
                if (state > -1)
                {
                    data = data.Where(k => k.state == state);
                }
                if (!string.IsNullOrEmpty(telephone))
                {
                    data = data.Where(k => k.telephone.Contains(telephone));
                }
                if (!string.IsNullOrEmpty(email))
                {
                    data = data.Where(k => k.email.Contains(email));
                }
                if (!string.IsNullOrEmpty(roles))
                {
                    data = data.Where(k => k.roles == roles);
                }
                if (crmUp != 0)
                {
                    data = data.Where(k => k.crmUpId == crmUp);
                }
                if (!string.IsNullOrEmpty(IdNo))
                {
                    data = data.Where(k => k.IdNo.Contains(IdNo));
                }
                if (!string.IsNullOrEmpty(registrationTime) && registrationTime.Contains(" - "))
                {
                    string[] registrationTimes = registrationTime.Split(new string[] { " - " }, StringSplitOptions.None);
                    DateTime startTime = Convert.ToDateTime(registrationTimes[0]);
                    DateTime endTime = Convert.ToDateTime(registrationTimes[1]);
                    data = data.Where(k => k.createDate > startTime && k.createDate < endTime);
                }
                if (page == 0 && limit == 0)
                {
                    res.Data = await data.OrderByDescending(k => k.state).ThenByDescending(k => k.createDate).ToArrayAsync();
                }
                else
                {
                    res.Data = await data.OrderByDescending(k => k.state).ThenByDescending(k => k.createDate).Skip((page - 1) * limit).Take(limit).ToArrayAsync();
                }
                res.Code = 0;
                res.Count = data.Count();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 选中上级
        public IActionResult SlectCRMUp()
        {
            return View();
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetSearchListJson(int page, int limit, string searchKey = "")
        {
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.CrmUsers
                           select new
                           {
                               id = y.Id,
                               isdel = y.Isdel,
                               loginName = y.LoginName,
                               fullName = y.Name,
                               telephone = y.Telephone,
                               email = y.Email,
                               level = y.Level
                           };
                data = data.Where(k => k.isdel == 0);
                if (!string.IsNullOrEmpty(searchKey))
                {
                    data = data.Where(k => k.fullName.Contains(searchKey) || k.telephone.Contains(searchKey) || k.email.Contains(searchKey));
                }
                res.Data = await data.OrderByDescending(k => k.id).Skip((page - 1) * limit).Take(limit).ToArrayAsync();
                res.Code = 0;
                res.Count = data.Count();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 添加用户

        public IActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Create(CrmUserExt item)
        {
            Result res = new Result();
            try
            {
                string code = publicService.GetCache<string>(item.LoginName);
                if (code != null)
                {
                    if (code != item.validCode)
                    {
                        res.Code = 1;
                        res.Msg = "validCodeError";
                    }
                    else
                    {
                        if (!TbUserExists(item.LoginName))
                        {
                            CrmUser model = new CrmUser();
                            model.LoginName = item.LoginName;
                            model.Name = item.Name;
                            model.Remark = item.Remark;
                            model.LoginPwd = SecurityUtil.EncryptPwd(item.LoginPwd);
                            model.Creator = User.UserName;
                            model.CreateDate = DateTimeUtil.Now;
                            model.CrmGroup = 0;
                            model.Isdel = 0;
                            model.Pid = 0;
                            model.Level = 0;
                            model.State = 1;
                            model.Source = 1;
                            _context.Add(model);
                            _context.SaveChanges();
                            TbUserRole userRole = new TbUserRole
                            {
                                RoleId = item.userRoles,
                                UserId = model.Id,
                                UserType = 1
                            };
                            _context.TbUserRoles.Add(userRole);

                            res.Code = 0;
                            res.Data = await _context.SaveChangesAsync();
                        }
                        else
                        {
                            res.Code = 1;
                            res.Msg = "loginNameExists";
                        }
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "validCodeError";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
                res.Msg = "submitFail";
                return new JsonResult(res);
            }
        }
        #endregion

        #region 发送邮件验证码
        /// <summary>
        /// 发送邮件验证码
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> SendValidateCode(string email)
        {
            Result res = new Result();
            try
            {
                string code = ValidateCode.CreateValidateCode(6);
                string title = "账号注册";
                if (TbUserExists(email))
                {
                    res.Code = 1;
                    res.Msg = "loginNameExists";
                    return new JsonResult(res);
                }
                //发送邮件
                await RM.Common.DotNetEamil.NetEmailClient.SendMailByConfig(email, title, RM.Common.DotNetEamil.NetEmailClient.GetCode(code, 15), "");
                res.Data = publicService.SetCache(email, code, TimeSpan.FromMinutes(15));
                res.Code = 0;
                res.Msg = "sendSuccess";
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑用户信息
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            CrmUser tbUser = await _context.CrmUsers.FindAsync(id);
            if (tbUser == null)
            {
                return NotFound();
            }
            return View(tbUser);
        }
        /// <summary>
        /// 编辑用户信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Edit(CrmUserExt item)
        {
            Result res = new Result();
            try
            {
                if (!TbUserExists(item.LoginName, item.Id))
                {
                    CrmUser model = await _context.CrmUsers.FindAsync(item.Id);
                    if (model != null)
                    {
                        if (!string.IsNullOrEmpty(item.LoginPwd))
                        {
                            model.LoginPwd = SecurityUtil.EncryptPwd(item.LoginPwd);
                        }
                        model.Name = item.Name;
                        model.Remark = item.Remark;

                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = "userNotExist";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "loginNameExists";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="updateType"></param>
        /// <returns></returns>
        public async Task<IActionResult> UpdatePwd(int? id, string updateType)
        {
            if (id == null)
            {
                return NotFound();
            }
            CrmUser tbUser = await _context.CrmUsers.FindAsync(id);
            if (tbUser == null)
            {
                return NotFound();
            }
            ViewBag.updateType = updateType;
            return View(tbUser);
        }

        /// <summary>
        /// 更新登录密码/交易密码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="loginPwd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpdatePwd(int id, string updateType, string newPwd)
        {
            Result res = new Result();
            try
            {
                CrmUser tbUser = await _context.CrmUsers.FindAsync(id);
                if (updateType == "loginPwd")
                {
                    tbUser.LoginPwd = SecurityUtil.EncryptPwd(newPwd);

                }
                else if (updateType == "tradePwd")
                {
                    tbUser.TradePwd = SecurityUtil.EncryptPwd(newPwd);

                }
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="intState"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpdateState(int id, int intState)
        {
            Result res = new Result();
            try
            {
                CrmUser tbUser = await _context.CrmUsers.FindAsync(id);
                tbUser.State = intState;

                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="intState"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> EditProgramme(int id, int returningRole, int programme)
        {
            Result res = new Result();
            try
            {
                CrmUser tbUser = await _context.CrmUsers.FindAsync(id);
                tbUser.Role = returningRole;
                if (programme == 0)
                {
                    tbUser.SchemeId = 0;
                }
                else
                {
                    tbUser.SchemeId = programme;
                }
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除用户
        /// <summary>
        /// 删除单个用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("Delete")]
        public JsonResult Delete(int id)
        {
            Result res = new Result();
            try
            {
                CrmUser tbUser = _context.CrmUsers.Find(id);
                tbUser.Isdel = 1;

                res.Code = 0;
                res.Data = _context.SaveChanges();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 查看用户详情
        public async Task<IActionResult> GetCRMAccountInfo(int id)
        {
            CrmUser crmUser = await _context.CrmUsers.FindAsync(id);
            if (crmUser == null)
            {
                return NotFound();
            }
            if (_context.TbUserRoles.Any(r => r.UserId == crmUser.Id && r.UserType == 1))
            {
                ViewBag.userRoles = _context.TbUserRoles.Where(r => r.UserId == crmUser.Id && r.UserType == 1).Select(k => k.RoleId).FirstOrDefault();
            }
            else
            {
                ViewBag.userRoles = 0;
            }
            if (crmUser.SchemeId != null)
            {
                ViewBag.SchemeId = crmUser.SchemeId;
            }
            else
            {
                ViewBag.SchemeId = 0;
            }
            List<CrmKyc> crmkycList = _context.CrmKycs.Where(k => k.State == 1).OrderBy(k => k.Sort).ToList();
            #region 个人信息
            List<CrmKyc> personalKycs = crmkycList.Where(k => k.Infotype == 1).ToList();
            CrmUserInfo personalUserInfos = _context.CrmUserInfos.OrderByDescending(k => k.CreateDate).FirstOrDefault(k => k.Type == 1 && k.CrmId == id && k.State == 2);
            if (personalUserInfos != null && !string.IsNullOrEmpty(personalUserInfos.Personal))
            {
                List<CrmKyc> personalInformations = JsonUtil.DeserializeJsonToList<CrmKyc>(personalUserInfos.Personal);
                ViewBag.personalType = personalUserInfos.State;
                ViewBag.personalInformations = personalInformations;
            }
            else
            {
                ViewBag.personalInformations = personalKycs;
            }
            #endregion

            #region 财务信息
            List<CrmKyc> financialInKycs = crmkycList.Where(k => k.Infotype == 2).ToList();
            CrmUserInfo userInfoFinancial = _context.CrmUserInfos.OrderByDescending(k => k.Id).FirstOrDefault(k => k.Type == 2 && k.CrmId == id && k.State == 2);
            if (userInfoFinancial != null && !string.IsNullOrEmpty(userInfoFinancial.Financial))
            {
                List<CrmKyc> financialInformations = JsonUtil.DeserializeJsonToList<CrmKyc>(userInfoFinancial.Financial);
                ViewBag.financialInformations = financialInformations;
            }
            else
            {
                ViewBag.financialInformations = financialInKycs;
                //List<CrmKyc> financialKycs = _context.CrmKycs.OrderBy(k => k.Sort).Where(k => k.Infotype == 2).ToList();
                //List<InputModel> inputModels = new List<InputModel>();
                //foreach (CrmKyc crmKyc in financialKycs)
                //{
                //    InputModel inputModel = new InputModel
                //    {
                //        name = crmKyc.Name,
                //        type = crmKyc.Type,
                //        value = ""
                //    };
                //    inputModels.Add(inputModel);
                //}
                //ViewBag.financialInformations = inputModels;
            }
            #endregion

            #region 身份信息
            List<CrmKyc> identityKycs = crmkycList.Where(k => k.Infotype == 3).ToList();
            CrmUserInfo userInfoIdentity = _context.CrmUserInfos.OrderByDescending(k => k.Id).FirstOrDefault(k => k.Type == 3 && k.CrmId == id && k.State == 2);
            if (userInfoIdentity != null && !string.IsNullOrEmpty(userInfoIdentity.Identity))
            {
                List<CrmKyc> identityInformations = JsonUtil.DeserializeJsonToList<CrmKyc>(userInfoIdentity.Identity);
                ViewBag.identityInformations = identityInformations;
            }
            else
            {
                ViewBag.identityInformations = identityKycs;
                //List<CrmKyc> identityKycs = _context.CrmKycs.OrderBy(k => k.Sort).Where(k => k.Infotype == 3).ToList();
                //List<InputModel> inputModels = new List<InputModel>();
                //foreach (CrmKyc crmKyc in identityKycs)
                //{
                //    InputModel inputModel = new InputModel
                //    {
                //        name = crmKyc.Name,
                //        type = crmKyc.Type,
                //        value = ""
                //    };
                //    inputModels.Add(inputModel);
                //}
                //ViewBag.identityInformations = inputModels;
            }
            #endregion
            return View(crmUser);
        }

        /// <summary>
        /// 编辑信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> EditCRMAccountInfo(CrmUserExt item)
        {
            Result res = new Result();
            try
            {
                CrmUser model = await _context.CrmUsers.FindAsync(item.Id);
                if (model != null)
                {
                    model.Name = item.Name;
                    model.Email = item.Email;
                    model.Telephone = item.Telephone;
                    model.State = item.State;
                    TbUserRole tbUserRole = _context.TbUserRoles.Where(r => r.UserId == item.Id && r.UserType == 1).FirstOrDefault();
                    if (tbUserRole != null)
                    {
                        if (tbUserRole.RoleId != item.userRoles)
                        {
                            _context.TbUserRoles.Remove(tbUserRole);
                        }
                    }
                    else if (item.userRoles > 0)
                    {
                        TbUserRole userRole = new TbUserRole
                        {
                            RoleId = item.userRoles,
                            UserId = item.Id,
                            UserType = 1
                        };
                        _context.TbUserRoles.Add(userRole);
                    }
                    res.Code = 0;
                    res.Msg = "submitSuccess";
                    res.Data = await _context.SaveChangesAsync();
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "submitFail";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 编辑信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> EditCRMInfo(int id, int type, string loginName, List<InputModel> inputModels)
        {
            Result res = new Result();
            try
            {
                CrmUserInfo crmUserInfo = await _context.CrmUserInfos.FirstOrDefaultAsync(k => k.CrmId == id);
                if (crmUserInfo != null)
                {
                    List<CrmKyc> subCrmKyc = new List<CrmKyc>();
                    List<CrmKyc> crmKycs = _context.CrmKycs.Where(k => k.State == 1 && k.Infotype == type).OrderBy(k => k.Sort).ToList();
                    //验证数据
                    foreach (InputModel model in inputModels)
                    {
                        if (model.type == "IMG")
                        {
                            model.name = model.name.Replace("Img", "");
                        }
                        CrmKyc crmKyc = crmKycs.FirstOrDefault(k => k.ControlId == model.name);
                        if (crmKyc != null)
                        {
                            if (crmKyc.Required == 0)
                            {
                                if (string.IsNullOrEmpty(model.value))
                                {
                                    res.Code = 1;
                                    res.Msg = "confirmNoRequired";
                                    return new JsonResult(res);
                                }
                            }
                        }
                        else
                        {
                            res.Code = 1;
                            res.Msg = "imformtionChange";
                            return new JsonResult(res);
                        }
                        crmKyc.Value = model.value;
                        subCrmKyc.Add(crmKyc);
                    }
                    switch (type)
                    {
                        case 1:
                            crmUserInfo.Personal = subCrmKyc.ToJson();
                            break;
                        case 2:
                            crmUserInfo.Financial = subCrmKyc.ToJson();
                            break;
                        case 3:
                            crmUserInfo.Identity = subCrmKyc.ToJson();
                            break;
                    }
                    res.Code = 0;
                    res.Msg = "submitSuccess";
                    res.Data = await _context.SaveChangesAsync();
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "submitFail";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="LoginName">登录名称</param>
        /// <param name="id">排除ID</param>
        /// <returns></returns>
        private bool TbUserExists(string LoginName, int id = 0)
        {
            if (id == 0)
                return _context.CrmUsers.Any(e => e.LoginName == LoginName);
            else
                return _context.CrmUsers.Any(e => e.Id != id && e.LoginName == LoginName);
        }
        #endregion

    }
}
